// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Collections.Generic;
using System.Linq;

namespace SnapObjects.Expressions
{
    internal class DynamicSignature : IEquatable<DynamicSignature>
    {
        private readonly int _hashCode;
        private readonly DynamicProperty[] _properties;

        public DynamicSignature(IEnumerable<DynamicProperty> properties)
        {
            _hashCode = 0;
            _properties = properties.ToArray();

            foreach (var property in properties)
            {
                _hashCode ^= property.Name.GetHashCode() ^ property.Type.GetHashCode();
            }
        }

        public override int GetHashCode()
        {
            return _hashCode;
        }

        public override bool Equals(object obj)
        {
            return obj is DynamicSignature signature && this.Equals(signature);
        }

        public bool Equals(DynamicSignature other)
        {
            if (_properties.Length != other._properties.Length)
            {
                return false;
            }

            for (var i = 0; i < _properties.Length; i++)
            {
                if (_properties[i].Name != other._properties[i].Name ||
                    _properties[i].Type != other._properties[i].Type)
                {
                    return false;
                }
            }

            return true;
        }
    }
}
